import os
import auto_log
import re
import shutil

ID_FILES_LIST_FROM_PATH = "files_list_from_path"
ID_COPY_AUTOTEST_MODULES = "copy_autotest_modules"
ID_CHECK_FILES_EXISTS = "check_files_exists"
ID_PREPARE = "prepare"
ID_COPY_UTILITIES = "copy_utilities"
ID_CREATE_RUN_BAT = "create_run_bat"
ID_GET_SYSTEM_DRIVE = "get_system_drive"
ID_ADD_CERTIFICATE = "add_certificate"

AUTOTEST_UTILITIES = "Autotest_Utilities"
AUTOTEST_RUN = "Autotest_Run"
AUTOTEST_LOGS = "Autotest_Logs"

def files_list_from_path(path, name, log = auto_log.LOG_TO_STDOUT):
    """
    get list of files from path
    """
    id = ID_FILES_LIST_FROM_PATH
    #--------------------------------------------------
    result = check_files_exists([path])
    if result != 0:
        message = result
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        return message
    #--------------------------------------------------
    files_list = []
    #--------------------------------------------------
    try:
        for root, dirs, files in os.walk(path):
            for file in files:
                if file.endswith(name):
                    files_list.append(root + "\\" + file)
    except:
        message = "Can't get list of files ends with: " + name + " from path: " + path
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        result = {"err": message, "res": []}
        return result
    
    result = {"err": 0, "res": files_list}
    return result
#----------------------------------------------------------------------

def search_startup_folder(letter, log = auto_log.LOG_TO_STDOUT):
    try:
        path = letter + "\\"
        for root, dirs, files in os.walk(path):
            for dir in dirs:
                if dir.endswith("Startup"):
                    line = root + "\\" + dir
                    if re.findall("Users", line):
                        return line
    except:
        return ""
    return ""
#----------------------------------------------------------------------

def copy_autotest_modules(modules_path, letter, log = auto_log.LOG_TO_STDOUT):
    id = ID_COPY_AUTOTEST_MODULES
    #--------------------------------------------------
    python_lib_path = letter + "\\Python31\\Lib"
    result = check_files_exists([modules_path, python_lib_path])
    if result != 0:
        message = result
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        return message
    #--------------------------------------------------
    result = files_list_from_path(modules_path, ".py", log)
    if result["err"] != 0:
        message = result["err"]
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        return message
    py_list = result["res"]
    #--------------------------------------------------
    result = files_list_from_path(modules_path, ".pyc", log)
    if result["err"] != 0:
        message = result["err"]
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        return message
    pyc_list = result["res"]
    #--------------------------------------------------
    if len(py_list) + len(pyc_list) == 0:
        message = "There are no *.py or *.pyc files in " + modules_path
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        return message
    #--------------------------------------------------
    for item in py_list:
        try:
            name = python_lib_path + "\\" + item.split("\\")[-1]
            if os.path.exists(name):
                os.remove(name)
            shutil.copy2(item, name)
        except:
            message = "Can't copy " + item
            auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
            return message
    #--------------------------------------------------
    for item in pyc_list:
        try:
            name = python_lib_path + "\\" + item.split("\\")[-1]
            if os.path.exists(name):
                os.remove(name)
            shutil.copy2(item, name)
        except:
            message = "Can't copy " + item
            auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
            return message
    #--------------------------------------------------
    return 0
#----------------------------------------------------------------------

def copy_utilities(utilities, letter, log = auto_log.LOG_TO_STDOUT):
    id = ID_COPY_UTILITIES
    if utilities == "":
        return 0
    #----------------------------------------------------------------------
    result = check_files_exists([letter, utilities])
    if result != 0:
        message = result
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        return message
    #----------------------------------------------------------------------
    util_folder = letter + "\\" + AUTOTEST_UTILITIES
    try:
        if os.path.exists(util_folder):
            shutil.rmtree(util_folder)
    except:
        message = "Can't create folder " + util_folder
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        return message
    try:
        shutil.copytree(utilities, util_folder)
    except:
        message = "Can't copy " + utilities + " to " + util_folder
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        return message
    return 0
#----------------------------------------------------------------------

def check_files_exists(files, log = auto_log.LOG_TO_STDOUT):
    id = ID_CHECK_FILES_EXISTS
    try:
        for item in files:
            if not os.path.exists(item):
                message = "Can't open " + item
                auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
                return message
    except:
        message = "Can't check files for existence"
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        return message
    return 0
#----------------------------------------------------------------------

def create_run_bat(script, parameters, letter, log = auto_log.LOG_TO_STDOUT):
    id = ID_CREATE_RUN_BAT
    result = check_files_exists([script, letter])
    if result != 0:
        message = result
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        return message
    #----------------------------------------------------------------------
    #create run.bat in startup folder
    startup_folder = search_startup_folder(letter, log)
    if startup_folder == "":
        message = "Can't find startup folder in " + letter + "\\"
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        return message
    run_bat = startup_folder + "\\run.bat"
    file = open(run_bat, "w")
    data = "cd %SYSTEMDRIVE%"+"\\" + AUTOTEST_RUN
    script_name = script.split("\\")[-1]
    data = data + "\n" + '"%s" %s' % (script_name, parameters)
    file.write(data)
    file.close()
    """
    try:
        file = open(run_bat, "w")
        data = "cd %SYSTEMDRIVE%"+"\\" + AUTOTEST_RUN
        data = data + "\n" + '"%s" %s' % (script_name, parameters)
        file.write(data)
        file.close()
    except:
        message = "Can't save file " + run_bat
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        return message
    """
    #----------------------------------------------------------------------
    #copy script to letter + "\\" + AUTOTEST_RUN
    run_folder = letter + "\\" + AUTOTEST_RUN
    try:
        if os.path.exists(run_folder):
            shutil.rmtree(run_folder)
        os.mkdir(run_folder)
    except:
        message = "Can't create folder " + run_folder
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        return message
    try:
        script_name = script.split("\\")[-1]
        script_path = run_folder + "\\" + script_name
        shutil.copy2(script, script_path)
    except:
        message = "Can't copy " + script + " to " + script_path
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        return message
    #----------------------------------------------------------------------
    
    return 0
#----------------------------------------------------------------------

def prepare(letter, modules, utilities, script, parameters, log = auto_log.LOG_TO_STDOUT):
    id = ID_PREPARE
    result = check_files_exists([letter, modules, utilities, script])
    if result != 0:
        message = result
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        return message
    #----------------------------------------------------------------------
    result = copy_autotest_modules(modules, letter)
    if result != 0:
        message = result
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        return message
    #----------------------------------------------------------------------
    result = copy_utilities(utilities, letter)
    if result != 0:
        message = result
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        return message
    #----------------------------------------------------------------------
    logs_folder = letter + "\\" + AUTOTEST_LOGS
    try:
        if os.path.exists(logs_folder):
            shutil.rmtree(logs_folder)
    except:
        message = "Can't create folder " + logs_folder
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        return message
    #----------------------------------------------------------------------
    result = create_run_bat(script, parameters, letter)
    if result != 0:
        message = result
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        return message
    #----------------------------------------------------------------------
    
    return 0
#----------------------------------------------------------------------

def get_system_drive(log = auto_log.LOG_TO_STDOUT):
    id = ID_GET_SYSTEM_DRIVE
    try:
        return ((auto_log.get_cmd_output("dir %SYSTEMDRIVE%\\")["out"].split("Directory of ")[1]).split("\\")[0])
    except:
        auto_log.write_result(log, "Can't get system drive", auto_log.STATUS_ERROR, id)
        return ("")
#----------------------------------------------------------------------

def add_certificate(certmgr, certificate, log = auto_log.LOG_TO_STDOUT):
    id = ID_ADD_CERTIFICATE
    system_drive = get_system_drive(log)
    if system_drive == "":
        message = "Can't get system drive"
        auto_log.write_result(log, message, auto_log.STATUS_ERROR, id)
        return message
    if not os.path.exists(system_drive + "\\windows\\system32\\slmgr.vbs"):
        return 0
    result = check_files_exists([certmgr, certificate])
    if result != 0:
        auto_log.write_result(log, result, auto_log.STATUS_ERROR, id)
        return result
    
    add_cert = '""%s" -add "%s" -c -s -r localMachine TrustedPublisher"' % (certmgr, certificate)
    result = auto_log.get_cmd_output(add_cert)
    if result["err"] != 0:
        message = "Cant add certificate " + certificate + " to localMachine TrustedPublisher"
        message = message + "\n" + "certmgr.exe error code = " + str(result["err"])
        message = message + "\n" + "certmgr.exe error output = " + str(result["output"])
        auto_log.write_result(log, message,  auto_log.STATUS_ERROR, id)
        return message
    return 0
#----------------------------------------------------------------------